#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

/**
 * Commande ls récursive
 */
void lsRec(char *dossierCourant) {

	struct stat buf;
	struct dirent *dentry;
	int status = 0, i = 0;

	DIR *dirp = opendir(dossierCourant);
	if (dirp == NULL) {
		fprintf(stderr, "repertoire inexistant\n");
		exit(EXIT_FAILURE);
	}

	printf("%s/ \n", dossierCourant);

	for (i = 0; i < 2; i++) {
		while ((dentry = readdir(dirp)) != 0) {
			char* tmp = (char*) malloc(
					sizeof(char)
							* (strlen(dossierCourant) + strlen(dentry->d_name))
							+ 3);
			strcpy(tmp, dossierCourant);
			strcat(tmp, "/");
			strcat(tmp, dentry->d_name);
			stat(tmp, &buf);
			// On parcourt l'ensemble des fichiers
			if ((strcmp(dentry->d_name, "..") != 0)
					&& (strcmp(dentry->d_name, ".") != 0)) {
				if (S_ISDIR(buf.st_mode) && (status == 1)) {
					lsRec(tmp);
				} else {
					if (status == 0)
						printf("%s\n", dentry->d_name);
				}
			}
		}

		status = 1;
		rewinddir(dirp);
	}

	closedir(dirp);

}

/**
 * Main
 */
//int main(int argc, char* argv[]) {
//
//	int i = 0;
//
//	if (argc > 1) {
//		for (i = 1; i < argc; i++) {
//			lsRec(argv[i]);
//			printf("\n-------------\n");
//		}
//	}
//
//	return EXIT_SUCCESS;
//}

